﻿using CommunityToolkit.Mvvm.Input;
using System.Threading;
using System.Threading.Tasks;
using UpperComputer.Application;
using UpperComputer.WPF.Entry.Common;
using UpperComputer.WPF.Entry.Common.Extensions;
using UpperComputer.WPF.Entry.Models;
using UpperComputer.WPF.Entry.Views;

namespace UpperComputer.WPF.Entry.ViewModels
{
    public class MenuOperationViewModel : OperationViewModel
    {
        private readonly IBaseMenuService _menuService;

        public IAsyncRelayCommand MenuSelectCommand { get; }

        private BaseMenuResultDto _menu = new();
        public BaseMenuResultDto Menu
        {
            get => _menu;
            set => SetProperty(ref _menu, value);
        }

        public NameValueModel<bool>[] IsActives { get; set; }

        private string _menuParentName;
        public string MenuParentName
        {
            get => _menuParentName;
            set => SetProperty(ref _menuParentName, value);
        }

        public MenuOperationViewModel(IBaseMenuService menuService,long id)
        {
            _menuService = menuService;
            Id = id;
            MenuSelectCommand = new AsyncRelayCommand(MenuSelectCommand_Execute);
            IsActives = new NameValueModel<bool>[] {
                new NameValueModel<bool>(Lang["是"], true),
                new NameValueModel<bool>(Lang["否"], false)
            };
        }

        private async Task MenuSelectCommand_Execute(CancellationToken cancellationToken)
        {
            MenuSelectControl menuSelectControl = Furion.App.GetService<MenuSelectControl>();
            object result = await menuSelectControl.ShowCustomDialog(Constant.DIALOG_IDENTIFIER_MENU);
            if (result is not null and BaseMenuResultDto)
            {
                BaseMenuResultDto menu = (BaseMenuResultDto)result;
                MenuParentName = menu.DisplayName;
                Menu.ParentCode = menu.Code;
            }
        }

        protected override async Task LoadAsync(object parameter, CancellationToken cancellationToken)
        {
            if (!IsAdd)
            {
                Menu = await _menuService.Get(Id, cancellationToken);
                MenuParentName = Menu.ParentCode;
            }
        }

        protected override async Task OkAsync(object parameter, CancellationToken cancellationToken)
        {
            if (!IsValidated || !Menu.IsValidated)
            {
                return;
            }
            await TryExecuteCommandAysnc(async cancellationToken =>
            {
                _ = IsAdd ? await _menuService.Post(Menu, cancellationToken)
                : await _menuService.Put(Menu, cancellationToken);
                CloseRootDialog(true);
            }, cancellationToken);
        }
    }
}